package gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import bd.ConsultasTableModel;
import bd.Resultado;
import bd.Servicios;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class VentanaConsulta extends javax.swing.JInternalFrame {
	private JPanel jPanel1;
	private JScrollPane jScrollPane1;
	private JButton btnRecargarTablas;
	private JTable tblLista;
	private JScrollPane scrLista;
	private JPanel pnlLista;
	private JTable tabla;
	private JButton btnClean;
	private JButton btnConsultar;
	private JTextArea jTextArea1;
	private JPanel jPanel2;
	private Servicios serv;
	protected Connection conexionBD = null;

	public VentanaConsulta() {
		super();
		initGUI();
		serv = Servicios.getServicios();
	}

	private void initGUI() {
		try {
			this.setPreferredSize(new java.awt.Dimension(864, 475));
			this.setBounds(0, 0, 864, 475);
			setVisible(true);
			{
				jPanel2 = new JPanel();
				getContentPane().add(jPanel2, BorderLayout.NORTH);
				jPanel2.setPreferredSize(new java.awt.Dimension(846, 141));
				jPanel2.setLayout(null);
				{
					jTextArea1 = new JTextArea();
					jPanel2.add(jTextArea1);
					jTextArea1.setBounds(17, 5, 331, 129);
					jTextArea1.setLineWrap(true);
					jTextArea1.setText("SELECT * \n" + "FROM Ciudad ");
				}
				{
					btnConsultar = new JButton();
					jPanel2.add(btnConsultar);
					btnConsultar.setText("Consultar");
					btnConsultar.setBounds(360, 20, 104, 35);
					btnConsultar.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							consultar();
						}
					});
				}
				{
					btnClean = new JButton();
					jPanel2.add(btnClean);
					btnClean.setText("Limpiar");
					btnClean.setBounds(360, 77, 104, 33);
					btnClean.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							jTextArea1.setText("");
							tabla.setModel(new DefaultTableModel(
									new String[][] { {}, {} }, new String[] {}));
						}
					});
				}
			}
			{
				jPanel1 = new JPanel();
				BorderLayout jPanel1Layout = new BorderLayout();
				getContentPane().add(jPanel1, BorderLayout.CENTER);
				jPanel1.setPreferredSize(new java.awt.Dimension(848, 178));
				jPanel1.setLayout(jPanel1Layout);
				{
					jScrollPane1 = new JScrollPane();
					jPanel1.add(jScrollPane1, BorderLayout.CENTER);
					jScrollPane1.setBounds(0, 0, 613, 309);
					{
						TableModel tablaModel = new DefaultTableModel(
								new String[][] { {}, {} }, new String[] {});
						tabla = new JTable();
						jScrollPane1.setViewportView(tabla);
						tabla.setModel(tablaModel);
						tabla.setAutoCreateRowSorter(true);
						tabla.setPreferredSize(new java.awt.Dimension(859, 285));
					}
				}
				{
					pnlLista = new JPanel();
					BorderLayout pnlListaLayout = new BorderLayout();
					pnlLista.setLayout(pnlListaLayout);
					jPanel1.add(pnlLista, BorderLayout.EAST);
					pnlLista.setPreferredSize(new java.awt.Dimension(262, 307));
					{
						scrLista = new JScrollPane();
						pnlLista.add(scrLista, BorderLayout.CENTER);
						{
							TableModel tblListaModel = new DefaultTableModel(
									new String[][] { {}, {} }, new String[] {
											"Tablas", "Atributos" });
							tblLista = new JTable();
							scrLista.setViewportView(tblLista);
							tblLista.setModel(tblListaModel);

							tblLista.addMouseListener(new MouseAdapter() {
								@Override
								public void mouseReleased(MouseEvent arg0) {
									int row = tblLista.rowAtPoint(arg0
											.getPoint());
									Object value = tblLista.getValueAt(row, 0);
									if (value != null)
										mostrarAtributos(value.toString());
								}

							});
						}
					}
					{
						btnRecargarTablas = new JButton();
						pnlLista.add(btnRecargarTablas, BorderLayout.SOUTH);
						btnRecargarTablas.setText("Recargar Tablas");
						btnRecargarTablas
								.addActionListener(new ActionListener() {
									public void actionPerformed(ActionEvent evt) {
										recargarTabla();
									}
								});
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void consultar() {
		Resultado r = serv.realizarConsulta(this.jTextArea1.getText().trim());
		if (r == null)
			JOptionPane.showMessageDialog(
					SwingUtilities.getWindowAncestor(this),
					"Modificacion realizada con exito.",
					"Modificacion exitosa", JOptionPane.INFORMATION_MESSAGE);
		else {
			if (r.fueExitoso()) {
				ConsultasTableModel modelo = new ConsultasTableModel();

				String[] columnas = r.getColumnas();
				String[] tipo = r.getTipos();
				try {
					for (int i = 0; i < columnas.length; i++) {
						String columnaNombre = columnas[i];
						Class columnaTipo;
						if (tipo[i].equals("java.sql.Time"))
							columnaTipo = Class.forName("java.lang.String");
						else
							columnaTipo = Class.forName(tipo[i]);

						boolean columnaEditable = false;
						modelo.agregarColumna(columnaNombre, columnaTipo,
								columnaEditable);
					}

					tabla.setModel(modelo);

					Vector<Object[]> filas = r.getFilas();
					for (Object[] f : filas)
						if (f != null)
							((ConsultasTableModel) this.tabla.getModel())
									.addRow(f);

				} catch (ClassNotFoundException e) {

				}
			} else {
				String e = "Error en la consulta SQL: "
						+ r.getExcepcion().getMessage();
				JOptionPane.showMessageDialog(
						SwingUtilities.getWindowAncestor(this), e + "\n",
						"Error al ejecutar la consulta.",
						JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	private void recargarTabla() {
		Resultado r = serv.realizarConsulta("show tables");

		if (r.fueExitoso()) {
			DefaultTableModel modelo = (DefaultTableModel) tblLista.getModel();

			modelo.setRowCount(0);

			Vector<Object[]> filas = r.getFilas();
			for (Object[] f : filas)
				if (f != null)
					modelo.addRow(f);

		} else {
			JOptionPane.showMessageDialog(
					SwingUtilities.getWindowAncestor(this), r.getExcepcion()
							+ "\n", "Error al ejecutar la consulta.",
					JOptionPane.ERROR_MESSAGE);
		}

	}

	protected void mostrarAtributos(String tabla) {
		Resultado r = serv.realizarConsulta("DESCRIBE " + tabla);
		if (r.fueExitoso()) {
			DefaultTableModel modelo = (DefaultTableModel) tblLista.getModel();

			for (int i = 0; i < modelo.getRowCount(); i++)
				modelo.setValueAt(null, i, 1);

			Vector<Object[]> filas = r.getFilas();
			int index = 0;
			for (Object[] f : filas)
				if (f != null) {
					modelo.setValueAt(f[0], index, 1);
					index++;
				}

		} else {
			JOptionPane.showMessageDialog(
					SwingUtilities.getWindowAncestor(this), r.getExcepcion()
							+ "\n", "Error al ejecutar la consulta.",
					JOptionPane.ERROR_MESSAGE);
		}
	}
}
